# -*- coding: utf-8 -*-
"""
Created on Wed Jul  3 09:05:20 2019

@author: frankwin7
"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import datetime  # For datetime objects
#import os.path  # To manage paths
#import sys  # To find out the script name (in argv[0])
import time

# Import the backtrader platform
import backtrader as bt
import pandas as pd
import empyrical as emp

import sys

class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass

sys.stdout = Logger("optstrategy_result.txt")
# Create a Stratey
class TestStrategy(bt.Strategy):
    params = (
        ('emaperiod', 745),
        ('upper', 30),
         ('lower', - 27),
       ('printlog', False),
    )

    def log(self, txt, dt=None, doprint=False):
        ''' Logging function fot this strategy'''
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close

        # To keep track of pending orders and buy price/commission
        self.order = None
        self.buyprice = None
        self.buycomm = None
        #self.lower = - 27
        #self.upper = 3

        # Add a MovingAverageSimple indicator
        self.ema = bt.indicators.ExponentialMovingAverage(
            self.datas[0], period=self.params.emaperiod)
        self.dpce = (self.dataclose / self.ema - 1) * 100

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return

        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))

                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:  # Sell
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))

            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

        # Write down: no pending order
        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return

        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))

    def next(self):
        # Simply log the closing price of the series from the reference
        #self.log('Close, %.2f' % self.dataclose[0])

        # Check if an order is pending ... if yes, we cannot send a 2nd one
        if self.order:
            return

        # Check if we are in the market
        if not self.position:

            # Not yet ... we MIGHT BUY if ...
            if self.dpce[0] < self.params.lower / 10:

                # BUY, BUY, BUY!!! (with all possible default parameters)
                self.log('BUY CREATE, %.2f' % self.dataclose[0])

                # Keep track of the created order to avoid a 2nd order
                self.order = self.buy()

            elif self.dpce[0] > self.params.upper / 10:
                # SELL, SELL, SELL!!! (with all possible default parameters)
                self.log('SELL CREATE, %.2f' % self.dataclose[0])

                # Keep track of the created order to avoid a 2nd order
                self.order = self.sell()
        else:
            if self.position.size < 0 and self.dpce[0] < self.params.lower / 10:
                # CLOSE (with all possible default parameters)
                
                self.log('CLOSE CREATE, Price:%.2f' %
                         (self.dataclose[0]
                          )
                     )
                
                # Keep track of the created order to avoid a 2nd order
                self.order = self.close()
            elif self.position.size > 0 and self.dpce[0] > self.params.upper / 10:
                # CLOSE (with all possible default parameters)
                
                self.log('CLOSE CREATE, Price:%.2f' %
                         (self.dataclose[0]
                          )
                     )
                
                # Keep track of the created order to avoid a 2nd order
                self.order = self.close()

    def stop(self):
        self.log('EMA Period: %2d, upper: %2d, lower: %2d, Ending Value %.2f' %
                 (self.params.emaperiod, self.params.upper, self.params.lower, self.broker.getvalue()), doprint=True)


if __name__ == '__main__':
    start = time.process_time()

    # Create a cerebro entity
    cerebro = bt.Cerebro(maxcpus = 1)

    # Add a strategy
    #cerebro.addstrategy(TestStrategy)
    strats = cerebro.optstrategy(
        TestStrategy,
        emaperiod=range(748, 751),
        upper = range(30, 33),
        lower = range(-28, - 25),
        )
    '''
    # Datas are in a subfolder of the samples. Need to find where the script is
    # because it could have been called from anywhere
    modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
    datapath = os.path.join(modpath, '../backtrader/datas/orcl-1995-2014.txt')

    # Create a Data Feed
    data = bt.feeds.YahooFinanceCSVData(
        dataname=datapath,
        # Do not pass values before this date
        fromdate=datetime.datetime(2000, 1, 1),
        # Do not pass values before this date
        todate=datetime.datetime(2000, 12, 31),
        # Do not pass values after this date
        reverse=False)

    # Add the Data Feed to Cerebro
    cerebro.adddata(data)
    '''
    dataframe = pd.read_csv('bitfinex_BTCUSD_min_20180601_20190531.csv', index_col=0, parse_dates=True)
    dataframe['openinterest'] = 0
    fromdate = datetime.datetime(2018, 6, 1, 0, 1)
    fromdate_str = fromdate.strftime('%Y/%m/%d')
    todate = datetime.datetime(2019, 5, 31, 23, 59)
    todate_str = todate.strftime('%Y/%m/%d')
    data = bt.feeds.PandasData(dataname=dataframe,
        fromdate = fromdate,
        todate = todate,
        timeframe = bt.TimeFrame.Minutes
        )
    # Add the Data Feed to Cerebro
    cerebro.adddata(data, name = 'BTCUSD')
    
    # Set our desired cash start
    cerebro.broker.setcash(1000.0)

    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.PercentSizer, percents = 95)

    # Set the commission
    cerebro.broker.setcommission(commission=0.0035)
    cerebro.addanalyzer(bt.analyzers.TimeReturn,  _name='TimeReturn', timeframe=bt.TimeFrame.Days)
    cerebro.addanalyzer(bt.analyzers.TimeReturn, data = data, _name='DataTimeReturn', timeframe=bt.TimeFrame.Days)
    strat_dict ={'emaperiod':[], 'upper':[], 'lower':[], '策略年化索丁诺比率':[], '比特币年化索丁诺比率':[]}

    # Run over everything
    results = cerebro.run()
    print('==================================================')
    for result in results:
        print('**************************************************')
        for strat in result:
            strat_daily_return = strat.analyzers.TimeReturn.get_analysis()
            data_daily_return = strat.analyzers.DataTimeReturn.get_analysis()
            strat_daily_return_s = pd.Series(strat_daily_return)
            data_daily_return_s = pd.Series(data_daily_return)
            strat_dict['emaperiod'].append(strat.p._getkwargs()['emaperiod'])
            strat_dict['upper'].append(strat.p._getkwargs()['upper'])
            strat_dict['lower'].append(strat.p._getkwargs()['lower'])
            #strat_dict['lower'].append(- 27)
            strat_sortino = round(emp.sortino_ratio(strat_daily_return_s, required_return = 0.01 / 365, period='daily'), 2)
            strat_dict['策略年化索丁诺比率'].append(strat_sortino)
            oracle_sortino = round(emp.sortino_ratio(data_daily_return_s, required_return = 0.01 / 365, period='daily'), 2)
            strat_dict['比特币年化索丁诺比率'].append(oracle_sortino)
            print(strat.p._getkwargs(), '年化索丁诺比率:策略:', strat_sortino, '比特币:', oracle_sortino)
    strat_df = pd.DataFrame(strat_dict)
    strat_best = strat_df[strat_df['策略年化索丁诺比率'] == strat_df['策略年化索丁诺比率'].max()]
    print('最优的emaperiod:', strat_best.iloc[0, 0], '最优的upper:', strat_best.iloc[0, 1], '最优的lower:', strat_best.iloc[0, 2],'最大的策略年化索丁诺比率:', strat_best.iloc[0, 3], '比特币年化索丁诺比率:', strat_best.iloc[0, 4])
    print('==================================================')

    end = time.process_time()
    t=end-start
    print("运行时间为：（秒）",t) 

